<?php

/*
 * Edit by shengxin
 * Click nbfs://nbhost/SystemFileSystem/Templates/Scripting/PHPClass.php to edit this template
 */

namespace app\api\controller;

use app\common\controller\Api;
use util\Http;
use app\common\model\ThirdUserModel;
use app\shop\model\BookingModel;
/**
 * Description of WxPlatform
 *
 * @author PC
 */
class Wxplatform extends Api{
    private function getWxApp(){
        return ['appid'=>'wx1d8452cddd1a058c','secret'=>'9a4b283b52f2040b1ae776999306b568'];
//        return ['appid'=>'wx7b689d9ad4e25098','secret'=>'ed03528be77f6ebb6c75ffc77225141b'];
    }
    private function getAccessToken(){
        $now = time();
        $cache = cache('wx_access_token');
        if($cache && $cache['expires_in']>$now){
            $access_token = $cache['access_token'];
            app('log')->write('from cache:'.$access_token);
        }else{
            $host = 'https://api.weixin.qq.com/cgi-bin/token';
            $wxData = $this->getWxApp();
            $wxData['grant_type']='client_credential';
            $resp = Http::get($host,$wxData);
            $data = json_decode($resp,true);
            $access_token = $data['access_token'];
            $data['expires_in'] += $now-60;
            cache('wx_access_token',$data);
        }
        return $access_token;
    }
    public function getPhoneNum(){
        $access_token = $this->getAccessToken();
        $code = $this->request->get('code');
        $openid = $this->request->get('openid');
        $url = 'https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token='.$access_token;
        $resp = Http::post($url,json_encode(['code'=>$code]));
//        $resp = '{"errcode":0,"phone_info":{"phoneNumber":15604081093}}';
        $data = json_decode($resp,true);
        if($data['errcode']==0){
            $model = new ThirdUserModel();
            $udata = $model->where('openid',$openid)->field('id')->find();
            $phone = $data['phone_info'];
            $phoneNumber = $phone['phoneNumber'];
            $udata->mobile = $phoneNumber;
            $udata->where('id',$udata->id)->update(['mobile'=>$phoneNumber]);
            $this->success('ok',['phoneNum'=>$phoneNumber]);
        }
        app('log')->error('resp');
        $this->error('获取失败');
    }
    
    public function login(){
        $code = $this->request->get('code');
        $url = 'https://api.weixin.qq.com/sns/jscode2session';
        $wxData = $this->getWxApp();
        $wxData['grant_type']='authorization_code';
        $wxData['js_code']=$code;
        //'{"session_key":"svF+BcNo9IFzrBU8HCBapg==","openid":"oNHkaxMYa8IqyvFvRFwzSDKz32eY"}';
        $rs = Http::get($url,$wxData);
        app('log')->info($rs);
        $data = json_decode($rs,true);
        //{"session_key":"svF+BcNo9IFzrBU8HCBapg==","openid":"oNHkaxMYa8IqyvFvRFwzSDKz32eY"}
        //login
        $unuid = isset($data['unionid'])??'';
        $openid = $data['openid'];
        
        $model = new ThirdUserModel();
        $udata = $model->where('openid',$openid)->find();
        $phone = '';
        if($udata){
            $model->session_key = $data['session_key'];
            $model->update();
            $phone = $udata['mobile'];
            $uid = $udata['id'];
        }else{
            $uid = $model->insert([
                'unionid'=>$unuid,
                'openid'=>$openid,
                'session_key'=>$data['session_key']
            ]);
        }
        $token = genRandomString(32);
        $tokenDb = new \app\common\model\TokenModel();
        $tokenDb->insert(['token'=>$token,'uid'=>$uid,'data'=> json_encode(['open_id'=>$openid]),'create_time'=>time()]);
        $this->success('ok',['loginUser'=>$openid,'token'=>$token,'phone_number'=>$phone]);
    }
//    
//    public function checkPhone(){
//        $openid = $this->request->get('openid');
//        $token= $this->request->get('token');
//        $model = new ThirdUserModel();
//        $data = $model->where('openid',$openid)->find()->toArray();
//        if($data['session_key']!=$token){
//            $model->where('openid',$openid)->update(['session_key'=>$token]);
//        }
//        $phone_number = 0;
//        if($data && $data['mobile']){
//            $phone_number = $data['mobile'];
//        }
//        $token = genRandomString(16);
//        $this->success('ok',['phone_number'=>$phone_number,'token'=>$token]);
//    }
    
    public function saveHead(){
        $url = $this->request->post('avatar');
        $model = new ThirdUserModel();
        $id = $this->dbToken();
        $data = $model->where('id',$id)->update(['avatar_url'=>$url]);
        $this->success('ok',$data);
    }
    
    public function getMyData(){
        $id = $this->dbToken();
        $model = new ThirdUserModel();
        $data = $model->where('id',$id)->find()->toArray();
        $uid = $data['id'];
        $bookingModel = new BookingModel();
        $data['order']=$bookingModel->getUserActiveData($uid);
        $this->success('ok',$data);
    }

}
